<template>
	<view class="container">
		<!-- 视频播放区域 -->
		<video ref="videoElement" autoplay muted playsinline></video>
		<button @click="toggleCamera">切换摄像头</button>
	</view>
</template>

<script setup>
	let videoStream = ref(null)
	let videoFacingMode = ref('user')
	async function startCamera() {
		try {
			// 请求访问用户摄像头
			const stream = await navigator.mediaDevices.getUserMedia({
				audio: false,
				video: {
					facingMode: this.videoFacingMode
				}
			});
			this.videoStream = stream;

			// 将视频流设置为video元素的源
			if (this.$refs.videoElement) {
				this.$refs.videoElement.srcObject = this.videoStream;
				this.$refs.videoElement.play();
			}
		} catch (error) {
			console.error('Error accessing camera:', error);
		}
	}

	function toggleCamera() {
		// 切换摄像头
		this.videoFacingMode = this.videoFacingMode === 'user' ? 'environment' : 'user';
		this.stopCamera();
		this.startCamera();
	}

	function stopCamera() {
		// 停止视频流
		if (this.videoStream) {
			this.videoStream.getTracks().forEach(track => track.stop());
			this.videoStream = null;
		}
	}




	//  data() {
	//    return {
	//      videoStream: null,
	//      videoFacingMode: 'user' // 默认使用前置摄像头
	//    };
	//  },
	//  methods: {
	//    async startCamera() {
	//      try {
	//        // 请求访问用户摄像头
	//        const stream = await navigator.mediaDevices.getUserMedia({
	//          audio: false,
	//          video: { facingMode: this.videoFacingMode }
	//        });
	//        this.videoStream = stream;

	//        // 将视频流设置为video元素的源
	//        if (this.$refs.videoElement) {
	//          this.$refs.videoElement.srcObject = this.videoStream;
	//          this.$refs.videoElement.play();
	//        }
	//      } catch (error) {
	//        console.error('Error accessing camera:', error);
	//      }
	//    },
	//    toggleCamera() {
	//      // 切换摄像头
	//      this.videoFacingMode = this.videoFacingMode === 'user' ? 'environment' : 'user';
	//      this.stopCamera();
	//      this.startCamera();
	//    },
	//    stopCamera() {
	//      // 停止视频流
	//      if (this.videoStream) {
	//        this.videoStream.getTracks().forEach(track => track.stop());
	//        this.videoStream = null;
	//      }
	//    }
	//  }
	//   ,
	//   mounted() {
	//     // 页面加载时启动摄像头
	//     this.startCamera();
	//   },
	//   beforeDestroy() {
	//     // 页面销毁前关闭摄像头
	//     this.stopCamera();
	//   }
	// };
</script>

<style scoped>
	.container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
	}

	video {
		width: 100%;
		max-width: 600px;
	}
</style>